<template>
  <div class="notification-badge" @click="toggleDropdown">
    <n-badge :value="unreadCount" :show="unreadCount > 0" :max="99">
      <n-icon :size="20" class="notification-icon">
        <NotificationsOutline />
      </n-icon>
    </n-badge>
    
    <!-- 通知下拉菜单 -->
    <transition name="dropdown-fade">
      <div v-if="dropdownVisible" class="notification-dropdown">
        <div class="notification-header">
          <h3>通知</h3>
          <div class="notification-actions">
            <NButton 
              v-if="hasUnreadNotifications" 
              text 
              size="small" 
              @click.stop="handleMarkAllAsRead"
            >
              全部已读
            </NButton>
            <NButton 
              text 
              size="small" 
              @click.stop="handleDeleteReadNotifications"
            >
              清除已读
            </NButton>
            <NButton 
              text 
              size="small" 
              @click.stop="viewAll"
            >
              查看全部
            </NButton>
          </div>
        </div>
        
        <div class="notification-content">
          <div v-if="loading" class="notification-loading">
            <n-icon class="is-loading"><Refresh /></n-icon>
            <span>加载中...</span>
          </div>
          
          <div v-else-if="error" class="notification-error">
            <span>{{ error }}</span>
            <n-button text size="small" @click.stop="refresh">重试</n-button>
          </div>
          
          <div v-else-if="notifications.length === 0" class="notification-empty">
            <span>暂无通知</span>
          </div>
          
          <div v-else class="notification-list">
            <div 
              v-for="notification in notifications" 
              :key="notification.id" 
              class="notification-item"
              :class="{ 'unread': isUnread(notification) }"
              @click="handleNotificationClick(notification)"
            >
              <div class="notification-item-header">
                <div class="notification-title">{{ notification.title }}</div>
                <div class="notification-time">{{ formatTime(notification.createTime) }}</div>
              </div>
              <div class="notification-item-content">{{ notification.content }}</div>
              <!-- 显示任务进度 -->
              <div v-if="notification.type === 'TASK' && notification.progress !== undefined" class="notification-progress">
                <div class="progress-bar">
                  <div 
                    class="progress-fill" 
                    :style="{ width: `${notification.progress}%` }"
                  ></div>
                </div>
                <span class="progress-text">{{ notification.progress }}%</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </transition>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { useMessage } from 'naive-ui'
import { NotificationsOutline,Refresh } from '@vicons/ionicons5'
import { useTaskNotificationManager } from '../../task/composables/useTaskNotificationManager'
import type { TaskNotification } from '../../../types/task-notification'
import { isUnread } from '../../../types/task-notification'

const router = useRouter()
const message = useMessage()
const dropdownVisible = ref(false)
// 使用通知管理器
const { 
  notifications, 
  unreadCount, 
  loading, 
  error, 
  hasUnreadNotifications,
  markAsRead, 
  markAllAsRead, 
  deleteReadNotifications,
  refresh
} = useTaskNotificationManager()

// 切换下拉菜单显示状态
const toggleDropdown = () => {
  dropdownVisible.value = !dropdownVisible.value
}

// 处理通知点击
const handleNotificationClick = async (notification: TaskNotification) => {
  try {
    // 标记为已读
    if (isUnread(notification)) {
      await markAsRead(notification.id)
    }
    
    // 关闭下拉菜单
    dropdownVisible.value = false
    
    // 根据任务类型跳转到相应页面
    if (notification.taskId && notification.taskType) {
      // 跳转到任务详情页
      router.push(`/tasks/${notification.taskType}/${notification.taskId}`)
    }
  } catch (err) {
    console.error('处理通知点击失败:', err)
    message.error('操作失败')
  }
}

// 查看全部通知
const viewAll = () => {
  dropdownVisible.value = false
  router.push('/notifications')
}

// 标记所有通知为已读
const handleMarkAllAsRead = async () => {
  try {
    await markAllAsRead()
    message.success('所有通知已标记为已读')
  } catch (err) {
    console.error('标记所有通知为已读失败:', err)
    message.error('操作失败')
  }
}

// 删除已读通知
const handleDeleteReadNotifications = async () => {
  try {
    await deleteReadNotifications()
    message.success('已删除所有已读通知')
  } catch (err) {
    console.error('删除已读通知失败:', err)
    message.error('操作失败')
  }
}

// 格式化时间
const formatTime = (timeStr: string) => {
  const time = new Date(timeStr)
  const now = new Date()
  const diff = now.getTime() - time.getTime()
  
  // 小于1分钟
  if (diff < 60 * 1000) {
    return '刚刚'
  }
  
  // 小于1小时
  if (diff < 60 * 60 * 1000) {
    return `${Math.floor(diff / (60 * 1000))}分钟前`
  }
  
  // 小于1天
  if (diff < 24 * 60 * 60 * 1000) {
    return `${Math.floor(diff / (60 * 60 * 1000))}小时前`
  }
  
  // 小于7天
  if (diff < 7 * 24 * 60 * 60 * 1000) {
    return `${Math.floor(diff / (24 * 60 * 60 * 1000))}天前`
  }
  
  // 超过7天显示具体日期
  return time.toLocaleDateString()
}

// 点击外部关闭下拉菜单
const handleClickOutside = (event: MouseEvent) => {
  const target = event.target as HTMLElement
  if (!target.closest('.notification-badge')) {
    dropdownVisible.value = false
  }
}

// 添加和移除点击事件监听器
onMounted(() => {
  document.addEventListener('click', handleClickOutside)
})

onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
})
</script>

<style scoped>
.notification-badge {
  position: relative;
  cursor: pointer;
  /* 移除 z-index: 103; */
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  transition: all 0.2s;
}

.notification-badge:hover {
  color: var(--accent-color);
}

.notification-icon {
  color: var(--text-primary);
  font-size: 20px;
  transition: all 0.2s;
}

.notification-badge:hover .notification-icon {
  color: var(--accent-color);
}

.notification-dropdown {
  position: absolute;
  top: calc(100% + 8px);
  right: -8px;
  width: 380px;
  background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
  border: 1px solid rgba(24, 160, 88, 0.2);
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12), 0 2px 8px rgba(0, 0, 0, 0.08);
  /* 移除 z-index: 1500; */
  overflow: hidden;
  backdrop-filter: blur(10px);
}

.dropdown-fade-enter-active,
.dropdown-fade-leave-active {
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
}

.dropdown-fade-enter-from,
.dropdown-fade-leave-to {
  opacity: 0;
  transform: translateY(-15px) scale(0.95);
}

.notification-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background: linear-gradient(135deg, #18a058 0%, #36ad6a 100%);
  color: white;
  border-bottom: none;
}

.notification-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.notification-actions {
  display: flex;
  gap: 12px;
}

.notification-actions :deep(.n-button) {
  color: white;
  border-color: rgba(255, 255, 255, 0.3);
  transition: all 0.3s ease;
}

.notification-actions :deep(.n-button:hover) {
  background-color: rgba(255, 255, 255, 0.2);
  transform: translateY(-1px);
}

.notification-content {
  max-height: 420px;
  overflow-y: auto;
  scrollbar-width: thin;
  scrollbar-color: rgba(24, 160, 88, 0.3) transparent;
}

.notification-content::-webkit-scrollbar {
  width: 6px;
}

.notification-content::-webkit-scrollbar-track {
  background: transparent;
}

.notification-content::-webkit-scrollbar-thumb {
  background: rgba(24, 160, 88, 0.3);
  border-radius: 3px;
}

.notification-content::-webkit-scrollbar-thumb:hover {
  background: rgba(24, 160, 88, 0.5);
}

.notification-loading,
.notification-error,
.notification-empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 32px 20px;
  gap: 12px;
  color: var(--n-text-color-2);
  background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
}

.notification-loading .is-loading {
  animation: spin 1s linear infinite;
  color: #18a058;
  font-size: 24px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.notification-list {
  padding: 8px;
}

.notification-item {
  padding: 16px;
  margin: 4px 0;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  background: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  position: relative;
  overflow: hidden;
}

.notification-item::before {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  height: 100%;
  width: 3px;
  background: transparent;
  transition: all 0.3s ease;
}

.notification-item:hover {
  background: linear-gradient(135deg, #ffffff 0%, #f0fdf4 100%);
  transform: translateX(4px);
  box-shadow: 0 4px 16px rgba(24, 160, 88, 0.15);
}

.notification-item:hover::before {
  background: linear-gradient(135deg, #18a058 0%, #36ad6a 100%);
}

.notification-item.unread {
  background: linear-gradient(135deg, #f0fdf4 0%, #dcfce7 100%);
  border-left: 3px solid #18a058;
  box-shadow: 0 2px 12px rgba(24, 160, 88, 0.1);
}

.notification-item.unread::before {
  background: linear-gradient(135deg, #18a058 0%, #36ad6a 100%);
}

.notification-item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.notification-title {
  font-weight: 600;
  font-size: 15px;
  color: var(--n-text-color-1);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 70%;
  transition: color 0.3s ease;
}

.notification-item:hover .notification-title {
  color: #18a058;
}

.notification-time {
  font-size: 12px;
  color: var(--n-text-color-3);
  background: rgba(24, 160, 88, 0.1);
  padding: 2px 8px;
  border-radius: 12px;
  font-weight: 500;
}

.notification-item-content {
  font-size: 14px;
  color: var(--n-text-color-2);
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  line-height: 1.5;
  transition: color 0.3s ease;
}

.notification-item:hover .notification-item-content {
  color: var(--n-text-color-1);
}

.notification-progress {
  display: flex;
  align-items: center;
  margin-top: 8px;
  gap: 8px;
}

.progress-bar {
  flex: 1;
  height: 4px;
  background-color: rgba(24, 160, 88, 0.1);
  border-radius: 2px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #18a058 0%, #36ad6a 100%);
  border-radius: 2px;
  transition: width 0.3s ease;
}

.progress-text {
  font-size: 12px;
  color: var(--n-text-color-3);
  min-width: 35px;
  text-align: right;
}
</style>